#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
using namespace std;
#define oops(msg) {perror(msg); exit(1);}


void testSocket(){
    struct sockaddr_in servadd ;
    struct hostent* hp;
    int sock_id , sock_fd;
    char message[100];
    int messlen;

    sock_id = socket(AF_INET,SOCK_STREAM,0);
    if(sock_id == -1){
        oops("error in open socket")
    }
    bzero(&servadd,sizeof(servadd));
    hp = gethostbyname("lifelong0811");
    bcopy(&servadd.sin_addr,&hp->h_addr,hp->h_length);
    servadd.sin_port = htons(9999);
    if(bind(sock_id,(sockaddr*)&servadd,sizeof(servadd))!= 0)
        oops("bind error")
    if(listen(sock_id,1) == -1)
        oops("listen error")
    while(1){
        sock_fd = accept(sock_id,0,0);
        if(sock_fd == -1)
            oops("accept")
        write(sock_fd,"hello",5);
        char buf[10] = {0};
        int r = read(sock_fd,buf,10);
        cout << r << endl;
        cout << buf << endl;
   }
}

void testSocketUnix(){
    struct sockaddr_un servaddr;
    servaddr.sun_family = AF_UNIX;
    strcpy(servaddr.sun_path,"/home/lifelong0811/test.vcc2");
    int fd = socket(AF_UNIX,SOCK_DGRAM,0);
    if( fd == -1){
        oops("socket error");
    }
    int r = bind(fd,(sockaddr*)&servaddr,sizeof(servaddr));
    if(r == -1){
        oops("bind error");
    }
    cout << "success\n";
//     r = write(fd,"hello",5);
     r = sendto(fd,"hello",5,0,0,0);
    cout << r << endl;
    cout << strerror(errno) <<endl;
    char buf [10]={0};
    r  = read(fd,buf,10);
    cout << r << endl;
    cout <<  buf << endl;
    while(1);
}
